import scala.collection.mutable

object ScoreManagementSystem extends App {
  // 1. 定义学生数据结构
  case class Student(
                      id: String,
                      name: String,
                      className: String,
                      math: Int,
                      chinese: Int,
                      english: Int,
                      physics: Int,
                      chemistry: Int
                    )

  // 班级和科目定义
  val classNames = List("高一(1)班", "高一(2)班", "高一(3)班", "高一(4)班")
  val subjects = List("数学", "语文", "英语", "物理", "化学")

  // 2. 生成测试数据（4个班级，每个班级30名学生）
  val random = new scala.util.Random
  val students = for {
    className <- classNames
    id <- 1 to 30
  } yield Student(
    // 修复：使用 formatted 替代 padLeft 实现补零
    id = s"${className.take(3)}${id.formatted("%02d")}",
    // 修复：className.last 可能取到括号，改为提取班级编号
    name = s"学生${className.substring(3, 4)}${id}",
    className = className,
    math = 50 + random.nextInt(50),     // 50-99分
    chinese = 50 + random.nextInt(50),
    english = 50 + random.nextInt(50),
    physics = 50 + random.nextInt(50),
    chemistry = 50 + random.nextInt(50)
  )

  // 3. 计算每个学生的总分和平均分
  val studentsWithStats = for (student <- students) yield {
    val total = student.math + student.chinese + student.english +
      student.physics + student.chemistry
    val avg = total.toDouble / 5
    (student, total, avg)  // (学生信息, 总分, 平均分)
  }

  println(s"已加载${students.size}名学生数据")

  // 4. 按班级统计各分数段人数（按平均分统计）
  val classScoreSegments = mutable.Map[String, Map[String, Int]]()

  for (className <- classNames) {
    val classStudents = studentsWithStats.filter(_._1.className == className)

    // 初始化各分数段计数器
    var aCount = 0  // 90+
    var bCount = 0  // 80-89
    var cCount = 0  // 70-79
    var dCount = 0  // 60-69
    var eCount = 0  // <60

    // 遍历统计
    for ((_, _, avg) <- classStudents) {
      if (avg >= 90) aCount += 1
      else if (avg >= 80) bCount += 1
      else if (avg >= 70) cCount += 1
      else if (avg >= 60) dCount += 1
      else eCount += 1
    }

    classScoreSegments(className) = Map(
      "90分以上" -> aCount,
      "80-89分" -> bCount,
      "70-79分" -> cCount,
      "60-69分" -> dCount,
      "60分以下" -> eCount
    )
  }

  // 5. 筛选优秀学生（所有科目及格且平均分≥85）
  val excellentStudents = for {
    (student, total, avg) <- studentsWithStats
    if student.math >= 60
    if student.chinese >= 60
    if student.english >= 60
    if student.physics >= 60
    if student.chemistry >= 60
    if avg >= 85
  } yield (student.name, student.className, avg, total)

  // 6. 计算班级各科平均分及排名
  val classSubjectAverages = classNames.map { className =>
    val classStudents = students.filter(_.className == className)
    val mathAvg = classStudents.map(_.math).sum.toDouble / classStudents.size
    val chineseAvg = classStudents.map(_.chinese).sum.toDouble / classStudents.size
    val englishAvg = classStudents.map(_.english).sum.toDouble / classStudents.size
    val physicsAvg = classStudents.map(_.physics).sum.toDouble / classStudents.size
    val chemistryAvg = classStudents.map(_.chemistry).sum.toDouble / classStudents.size

    (className, Map(
      "数学" -> mathAvg,
      "语文" -> chineseAvg,
      "英语" -> englishAvg,
      "物理" -> physicsAvg,
      "化学" -> chemistryAvg
    ))
  }.toMap

  // 7. 输出统计结果
  // 7.1 第一个班级的分数段统计
  val firstClass = classNames.head
  println(s"\n===== $firstClass 分数段统计 =====")
  classScoreSegments(firstClass).foreach { case (segment, count) =>
    println(f"$segment：$count 人")
  }

  // 7.2 优秀学生列表
  println(s"\n===== 优秀学生（共${excellentStudents.size}人） =====")
  excellentStudents.take(5).foreach { case (name, cls, avg, total) =>
    println(f"$name（$cls）：总分$total，平均分${avg}%.1f")
  }

  // 7.3 各班数学平均分排名
  println("\n===== 各班数学平均分排名 =====")
  classSubjectAverages.toList
    .sortBy(-_._2("数学"))
    .zipWithIndex
    .foreach { case ((cls, avgs), idx) =>
      println(f"第${idx + 1}名：$cls，平均分${avgs("数学")}%.1f")
    }

  // 7.4 年级总分前10名
  println("\n===== 年级总分前10名 =====")
  studentsWithStats.sortBy(-_._2).take(10).zipWithIndex.foreach { case ((s, total, avg), idx) =>
    println(f"第${idx + 1}名：${s.name}（${s.className}），总分$total，平均分$avg%.1f")
  }
}